#!/bin/zsh -Ndefgku
#
# Scripts/format
# mas
#
# Copyright © 2025 mas-cli. All rights reserved.
#
# Automatically formats & fixes style violations using various tools.
#
# Please keep in sync with Scripts/lint.
#

. "${0:A:h}/_setup_script"

print_notice '🧹 Formatting' "${@}"

ensure_command_available markdownlint-cli2 swiftformat swiftlint

zmodload zsh/zutil
zparseopts -D -A received_flag A

export -r MAS_INSTALL_METHOD=format

printf -- $'--> 🕊​ SwiftFormat\n'
script -q /dev/null swiftformat --strict --markdown-files format-strict . |
 (grep -vxE '(?:\^D\x08{2})?Running SwiftFormat\.{3}\r|Reading (?:config|swift-version) file at .*|\x1b\[32mSwiftFormat completed in \d+(?:\.\d+)?s\.\x1b\[0m\r|0/\d+ files formatted\.\r' || true)

printf -- $'--> 🦅 SwiftLint\n'
swiftlint --fix --quiet --reporter relative-path

# shellcheck disable=SC1046,SC1047,SC1072,SC1073
if ! [[ -v 'received_flag[-A]' ]]; then
	printf -- $'--> 🔬 SwiftLint Analyze\n'
	# shellcheck disable=SC1036
	swiftlint analyze --fix --quiet --reporter relative-path --compiler-log-path\
	 =(xcodebuild -scheme mas -destination "platform=macOS,arch=$(arch),variant=macos" 2>&1)
fi

printf -- $'--> 〽️ Markdown\n'
markdownlint-cli2 --fix -- ***/*.md(.)

printf -- $'--> 🚷 Non-Executables\n'
readonly -a non_executables=(Scripts/***/*(N.^f+111))
if (("${#non_executables[@]}")); then
	chmod -vv a+x "${non_executables[@]}"
	exit 1
fi
